<?php

namespace App\Services\GoldCoin;


use App\Constants\ExpenseType;
use App\Constants\IncomeType;
use App\Exception\MessageException;
use App\Model\IncomeExpense;
use App\Model\User;
use App\Utils\FunUtil;
use App\Utils\LoggerUtil;
use Hyperf\DbConnection\Db;

class ExchangeService
{

    /**
     * Note - 查询金币和积分
     * DateTime 2024/8/12 10:49
     * User Admin
     * @param $uid
     * @param array $params
     * @return array
     */
    public function queryGiftCount($uid, array $params)
    {
        // $data = $userModel->find('id as uid,nickname,gift_count,integrate_usable_count', 'id = ?', [$uid]);
        $data = User::query()->find($uid, ['id as uid', 'nickname', 'gift_count', 'integrate_usable_count']);
        $data['gift_count'] = intval($data['gift_count']);
        $data['integrate_usable_count'] = $data['integrate_usable_count'] > 0 ? intval($data['integrate_usable_count']) : 0;
        $data['actual_amount'] = intval(round(($data['integrate_usable_count'] - $data['integrate_usable_count'] * 0.06) / GOLD_RATIO, 2));
        if ($params['language'] == 'zh-cn') {
            $data['content'] = "1、账户收益余额可进行兑换消费货币" . PHP_EOL . "2、1积分可兑换1金币" . PHP_EOL . "3、部分活动收入不可兑换金币" . PHP_EOL . "4、只能兑换整数的金币";
        } elseif ($params['language'] == 'zh-hk') {
            $data['content'] = "1、收益餘額可進行兌換消費貨幣" . PHP_EOL . "2、1積分可兌換1金幣" . PHP_EOL . "3、部分活動收入不可兌換金幣" . PHP_EOL . "4、只能兌換整數的金幣";
        } else {
            $data['content'] = "1、Account balance can be exchanged for consumption currency" . PHP_EOL . "2、1 point can be exchanged for 1 coin" . PHP_EOL . "3、Part of the activity income cannot be exchanged for coins" . PHP_EOL . "4、Only exchange coins that are integers";
        }

        if (!empty($data)) {
            // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => $data), '获取金币、积分成功');
            return formatData(array('result' => 1, 'msg' => $data));
        } else {
            // Tool::JSON(\CodeData::NEED_TIPS, '', '用户不存在');
            throw new MessageException('用户不存在');
        }
    }


    /**
     * Note - 兑换金币、积分
     * DateTime 2024/8/12 11:05
     * User Admin
     * @param $uid
     * @param array $params
     */
    public function exchangeGiftCount($uid, array $params)
    {
        //兑换数目
        $exchange_num = $params['exchange_num'];
        //渠道
        $channel = $params['channel'] ?? '';
        //系统类型
        $from = $params['from'] ?? 0;
        //包名
        $package = $params['package'] ?? '';
        //版本号
        $version_code = $params['version_code'] ?? 0;

        // $incomeExpenseModel = new IncomeExpenseModel();
        try {
            $ret = User::query()->find($uid, ['gift_count', 'integrate_usable_count']);
            if ($ret['integrate_usable_count'] < $exchange_num) {
                // Tool::JSON(\CodeData::NEED_TIPS, '', '当前账户余额，不可兑换金币');
                throw new MessageException('当前账户余额，不可兑换金币');
            }
            Db::beginTransaction();
            // 扣除积分增加用户金币
            $update_result = User::query()->where('id', $uid)->update([
                'gift_count' => Db::raw('gift_count + ' . $exchange_num),
                'integrate_usable_count' => Db::raw('integrate_usable_count - ' . $exchange_num)
            ]);
            if ($update_result) {
                $ip = FunUtil::getClientIp();
                $ctime = time();
                // 收入金币
                $gift_count_income_expense = [
                    'uid' => $uid,
                    'type' => 1, // 1:收入 2:支出
                    'sub_type' => IncomeType::EXCHANGE_GOLD, // 兑换金币
                    'amount_type' => 1,
                    'amount' => $exchange_num,
                    'account' => bcadd($ret['gift_count'], $exchange_num, 2),
                    'ctime' => $ctime,
                    'ip' => $ip,
                    'from' => $from,
                    'package' => $package,
                    'version_code' => $version_code,
                    'channel' => $channel,
                ];
                $gift_count_result = IncomeExpense::query()->insert($gift_count_income_expense);
                if ($gift_count_result) {
                    //支出积分
                    $integrate_income_expense = [
                        'uid' => $uid,
                        'type' => 2, // 1:收入 2:支出
                        'sub_type' => ExpenseType::EXCHANGE_GOLD_OUT, // 兑换金币
                        'amount_type' => 2,
                        'amount' => $exchange_num,
                        'account' => bcsub($ret['integrate_usable_count'], $exchange_num, 2),
                        'ctime' => $ctime,
                        'ip' => $ip,
                        'from' => $from,
                        'package' => $package,
                        'version_code' => $version_code,
                        'channel' => $channel,
                    ];
                    $integrate_result = IncomeExpense::query()->insert($integrate_income_expense);
                    if ($integrate_result) {
                        Db::commit();
                        return formatData(array('result' => 1, 'msg' => ''));
                    }
                    // LoggerUtil::write('exchangeGiftCount', '插入积分支出记录失败');
                    throw new \Exception('插入积分支出记录失败');

                }
                // LoggerUtil::write('exchangeGiftCount', '插入金币收入记录失败');
                throw new \Exception('插入金币收入记录失败');
            }
            // LoggerUtil::write('exchangeGiftCount', '更新金币、积分失败');
            throw new \Exception('更新金币、积分失败');
        } catch (\Exception $e) {
            LoggerUtil::write('exchangeGiftCount', $e->getMessage());
            Db::rollBack();
            throw new MessageException('兑换失败');
        }
    }
}